package com.piggymetrics.gateway;

import com.gaea.tracker.GatewayTracker;
import com.netflix.util.Pair;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;

public class MyPostFilter extends ZuulFilter {

  /**
   * 过滤器执行的具体逻辑
   * 只有URL后面有accToken的才被允许访问
   */
  public Object run() {
    Log LOG = LogFactory.getLog(MyPostFilter.class);
    //1.记录从服务器返回
    RequestContext ctx = getCurrentContext();
    Map<String, Collection<String>> headers = new HashMap<String, Collection<String>>();
    for (Pair<String, String> pair : ctx.getOriginResponseHeaders()) {
      Collection<String> strings = new HashSet<String>();
      strings.add(pair.second());
      headers.put(pair.first(), strings);
    }
    GatewayTracker tracker = GatewayTracker.newInstance("gateway");
    tracker.trackBackInEvent(headers, ctx.getResponseStatusCode() + "");

    LOG.info("status code is " + ctx.getResponseStatusCode());

    //2.记录返回客户端
    tracker.trackBackOutEvent(ctx.getResponse());


    return null;
  }

  /**
   * 判断过滤器是否需要被执行
   */
  public boolean shouldFilter() {
    return true;
  }

  /**
   * 过滤器执行顺序,数字越小优先级越高
   */
  public int filterOrder() {
    return 0;
  }

  /*
   * 定义过滤器类型，决定该规则处理请求的哪个生命周期执行，有以下四个阶段：
   * pre: 在请求被路由之前执行
   * route : 在路由请求调用
   * post : 在route和err之后被调用
   * error：在处理请求发生错误时调用
   */
  public String filterType() {
    return "post";
  }
}
